<!-- Joystick.vue -->
<template>
  <div class="joystick-container" @mousedown="startDrag" @touchstart="startDrag">
    <div class="joystick-base">
      <div class="joystick-thumb" :style="thumbStyle" @mousemove="onDrag" @mouseup="endDrag" @touchmove="onDrag" @touchend="endDrag"></div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      centerX: 50,
      centerY: 50,
      radius: 40,
      thumbX: 50,
      thumbY: 50, // 新增：垂直方向的位置
      isDragging: false,
    };
  },
  computed: {
    thumbStyle() {
      return {
        transform: `translate(${this.thumbX - this.centerX}px, ${this.thumbY - this.centerY}px)`,
      };
    },
  },
  methods: {
    startDrag(event) {
      this.isDragging = true;
      this.updateThumbPosition(event);
    },
    onDrag(event) {
      if (this.isDragging) {
        this.updateThumbPosition(event);
      }
    },
    endDrag() {
      this.isDragging = false;
      this.resetThumbPosition();
    },
    updateThumbPosition(event) {
      const rect = event.target.getBoundingClientRect();
      let x = event.clientX || event.touches[0].clientX;
      let y = event.clientY || event.touches[0].clientY;

      x -= rect.left;
      y -= rect.top;

      // 计算相对于中心点的距离
      const deltaX = x - this.centerX;
      const deltaY = y - this.centerY;
      const distance = Math.sqrt(deltaX ** 2 + deltaY ** 2);

      // 限制在半径范围内
      if (distance > this.radius) {
        this.thumbX = this.centerX + (deltaX / distance) * this.radius;
        this.thumbY = this.centerY + (deltaY / distance) * this.radius;
      } else {
        this.thumbX = x;
        this.thumbY = y;
      }

      // 发送归一化的方向值
      this.$emit('move', {
        x: (this.thumbX - this.centerX) / this.radius,
        y: (this.thumbY - this.centerY) / this.radius,
      });
    },
    resetThumbPosition() {
      this.thumbX = this.centerX;
      this.thumbY = this.centerY;
      this.$emit('move', { x: 0, y: 0 });
    },
  },
};
</script>

<style scoped>
.joystick-container {
  position: absolute;
  bottom: 20px;
  right: 20px;
  width: 100px;
  height: 100px;
  cursor: pointer;
}

.joystick-base {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
}

.joystick-thumb {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  transition: transform 0.1s ease;
}
</style>